package net

import (
	"bufio"
	"corelib/log"
	"corelib/parse"
	"net"
)

type TcpClient struct {
	remoteAddr string
	conn       net.Conn
	reader     *bufio.Reader
	onMsg      func(b []byte, c Conn)
}

func (t *TcpClient) Start() error {
	var err error
	t.conn, err = net.Dial("tcp", t.remoteAddr)
	if err != nil {
		return err
	}
	t.reader = bufio.NewReader(t.conn)
	go func() {
		defer t.Close()
		var msg []byte
		for {
			msg, err = t.Recv()
			if err != nil {
				panic(err)
			}
			if t.onMsg != nil {
				t.onMsg(msg, t)
			} else {
				log.Debug("recvMsg: %v", msg)
			}
		}
	}()
	return nil
}

func (t *TcpClient) Recv() ([]byte, error) {
	return parse.MsgUnpackDemo(t.reader)
}

func (t *TcpClient) Send(b []byte) (n int, err error) {
	return t.conn.Write(parse.MsgPackDemo(b))
}

func (t *TcpClient) SetMsgHandle(f func(b []byte, c Conn)) {
	t.onMsg = f
}

func (t *TcpClient) Close() error {
	return t.conn.Close()
}

func NewTcpClient(remoteAddr string) *TcpClient {
	return &TcpClient{remoteAddr: remoteAddr}
}
